<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      <el-table :data="rolsList" stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row
              :class="[i1===0?'bdtop':'','bdbottom','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="handleClose(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2===0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="handleClose(scope.row,item2.id)"
                      type="success"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag
                      closable
                      @close="handleClose(scope.row,item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="edtDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-s-tools"
              @click="setRight(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加文本框区域 -->
      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="30%" @close="addhandleClose">
        <el-form ref="rolesFormRef" :model="addForm" label-width="80px" :rules="addRoleRules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 文本框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDialog">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色文本框区域 -->
      <el-dialog title="添加角色" :visible.sync="editDialogVisible" width="30%">
        <el-form ref="editFormRef" :model="editFormList" label-width="80px" :rules="editFormRules">
          <el-form-item label="角色名称">
            <el-input v-model="editFormList.roleName" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editFormList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialogSub">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色文本框 -->
      <el-dialog
        title="提示"
        :visible.sync="setDialogVisible"
        width="30%"
        @close="setRightDialogClosed"
      >
        <el-tree
          :data="setRightList"
          show-checkbox
          default-expand-all
          :default-checked-keys="addRightList"
          node-key="id"
          ref="setTreeRef"
          :props="defaultProps"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRightSub">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolsList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      setDialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      addRoleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 5, max: 15, message: "长度在 5 到 15 个字符", trigger: "blur" }
        ]
      },

      // 编辑数据
      editFormList: [],
      // 编辑表单验证
      editFormRules: {
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 5, max: 15, message: "长度在 5 到 15 个字符", trigger: "blur" }
        ]
      },
      // 分配权限
      setRightList: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      addRightList: [],
      roleId: ""
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolsList = res.data;
      this.$message.success("获取角色列表成功");
    },
    // 删除三级分配权限
    async handleClose(role, id) {
      // console.log(role);
      // console.log(id);
      const confirmStr = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.message.error("取消权限失败");
      }
      role.children = res.data;
    },
    addhandleClose() {
      // console.log(this);
      this.$refs.rolesFormRef.resetFields();
    },
    // 添加角色
    addDialog() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addForm);
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加角色失败");
        this.getRolesList();
        this.addDialogVisible = false;
        this.$message.success("添加角色成功");
      });
    },
    // 编辑角色
    async edtDialog(id) {
      // 先通过id获取到
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.editFormList = res.data;
      this.editDialogVisible = true;
    },
    // 提交编辑
    editDialogSub() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editFormList.roleId,
          this.editFormList
        );
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.editFormList = res.data;
        this.getRolesList();
        this.editDialogVisible = false;
      });
    },
    // 删除角色
    async delRoles(id) {
      // console.log(id);
      const a = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(a);
      if (a !== "confirm") return;
      const { data: res } = await this.$http.delete("roles/" + id);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.getRolesList();
    },
    // 分配权限
    async setRight(node) {
      const { data: res } = await this.$http.get("rights/tree");
      console.log(res);
      this.setRightList = res.data;
      this.roleId = node.id;
      this.getRightSub(node, this.addRightList);
      this.setDialogVisible = true;
    },
    // 点击确定按钮 角色授权
    getRightSub(node, arr) {
      // console.log(node);
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getRightSub(item, arr);
      });
      // console.log(this.addRightList);
    },
    // 置空
    setRightDialogClosed() {
      this.addRightList = [];
    },
    // 确定按钮发起角色分配请求
    async setRightSub() {
      // console.log(this);

      const keys = [
        ...this.$refs.setTreeRef.getCheckedKeys(),
        ...this.$refs.setTreeRef.getHalfCheckedKeys()
      ];
      // console.log(this.addRightList);
      const idStr = keys.join(",");
      console.log(idStr);

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("添加失败");
      this.setDialogVisible = false;
      this.getRolesList();
    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
